/*
 * @Author: byron
 * @Date: 2021-09-25 22:11:00
 * @LastEditTime: 2021-10-05 14:29:15
 */
import axios from 'axios'
import { Loading } from 'element-ui'
import { confirm } from '@/base/confirm'
// import store from '@/store'

const BASE_URL = 'https://netease-music-api.fe-mm.com/'
let loading
let loadingCount = 0

// 不带全局loading的请求实例
export const requestWithoutLoading = createBaseInstance()

// 传入函数是因为需要在处理请求结果handleResponse之前处理loading
// 所以要在内部插入loading拦截器的处理逻辑
export const request = createBaseInstance()
mixinLoading(request.interceptors)

// 通用的axios实例
function createBaseInstance() {
    const instance = axios.create({
        baseURL: BASE_URL,
        timeout: 10000,
    })

    instance.interceptors.response.use(handleResponse, handleError)
    return instance
}

// 请求错误函数
function handleError(e) {
    // console.log('this', this)
    confirm(e.message, '出错啦~')
    // 此时this不被定义
    // this.$confirm('请求失败', e.message)

    throw e
}

// 请求成功函数
function handleResponse(response) {
    return response.data
}

// 带全局loading的请求实例

// const SET_AXIOS_LOADING = 'global/setAxiosLoading'
function mixinLoading(interceptors) {
    interceptors.request.use(loadingRequestInterceptor)
    interceptors.response.use(
        loadingResponseInterceptor,
        loadingResponseErrorInterceptor
    )

    // 加载loading实例
    function loadingRequestInterceptor(config) {
        if (!loading) {
            loading = Loading.service({
                target: 'body',
                background: 'transparent',
                text: '载入中',
            })
            // store.commit(SET_AXIOS_LOADING, true)
        }
        loadingCount++
        return config
    }

    // 一级响应拦截器
    function handleResponseLoading() {
        loadingCount--
        // 当当前页面全部请求完毕之后关闭loading的加载
        if (loadingCount === 0) {
            loading.close()
            loading = null
            // store.commit(SET_AXIOS_LOADING, false)
        }
    }

    function loadingResponseInterceptor(response) {
        handleResponseLoading()
        return response
    }

    function loadingResponseErrorInterceptor(e) {
        handleResponseLoading()
        throw e
    }
}
